<?php

namespace App\Http\Traits;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Article;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\News;
use EasyWeChat\OpenPlatform\Guard;
use Illuminate\Http\Request;
use EasyWeChat\Encryption\Encryptor;
use EasyWeChat\Support\Collection;
use EasyWeChat\Message\Text;
use Illuminate\Support\Facades\Session;

trait WechatTrait
{
    private $application = null;

    /**
     * @param null $isOpenPlateform
     * @return Application
     *
     * 微信api初始化
     */
    public function wechatInit($isOpenPlateform = null)
    {
        $options = $this->getOptions($isOpenPlateform);

        if (!empty($this->paymentResolver)) {
            $payoption = call_user_func($this->paymentResolver);
            if (!empty($payoption) && is_array($payoption)) {
                $options = array_merge($options, ['payment' => $payoption]);
            }
        }

        //授权
        if (!empty($this->oauthResolver)) {
            $oauthOption = call_user_func($this->oauthResolver);
            if (!empty($oauthOption) && is_array($oauthOption)) {
                $options = array_merge($options, ['oauth' => $oauthOption]);
            }
        }

        if (!empty($this->application)) {
            return $this->application;
        }

        return $this->application = new Application($options);
    }

    /**
     * @param callable $closure
     * 设置回掉函数
     */
    public function setPaymentResolver(callable  $closure)
    {
        $this->paymentResolver = $closure;
    }


    /**
     * @param callable $closure
     * 设置授权回调函数
     */
    public function setOauthResolver(callable  $closure)
    {
        $this->oauthResolver = $closure;
    }


    /**
     * @param null $isOpenPlateform
     * @return array
     *
     * 获取配置信息
     */
    public function getOptions($isOpenPlateform = null)
    {
        $options = [
            'debug' => true,
            'app_id' => config('wechatoauth.app_id'),
            'secret' => config('wechatoauth.secret'),
            'token' => config('wechatoauth.token'),
            'aes_key' => config('wechatoauth.aes_key'),
            'log' => [
                'level' => 'debug',
                'file' => storage_path('logs/easywechat.log')
            ]
        ];
        if ($isOpenPlateform) {
            $options['open_platform'] =
                ['app_id' => config('wechatoauth.app_id'),
                    'secret' => config('wechatoauth.secret'),
                    'token' => config('wechatoauth.token'),
                    'aes_key' => config('wechatoauth.aes_key')];
        }

        return $options;
    }


    /**
     * @return Application
     * 获取消息微信开发平台实例
     */
    private function createMessageApplication($appid)
    {
        $openPlatform = $this->wechatInit(true)->open_platform;
        $app = get_wechat_app($appid);
        return $openPlatform->createAuthorizerApplication($appid, $app->authorizer_refresh_token);
    }


    /**
     * @return Application
     * 获取登录开发平台微信应用实例
     */
    private function createLoginApplication($tenantId)
    {
        $openPlatform = $this->wechatInit(true)->open_platform;
        $app = get_wechat_options($tenantId);
        return empty($app) ? null : $openPlatform->createAuthorizerApplication($app->appid, $app->authorizer_refresh_token);
    }

    /**
     * @param $text
     * @return string
     * 过滤文本素材
     */
    private function filterText($text)
    {
        $find = array("&amp;", "&quot;", "&#039;", "&lt;", "&gt;", "&lt;", "&gt;", "&nbsp;", "<br />", "&ldquo;", "&rdquo;");
        $replace = array("&", '"', "'", "<", ">", "%3C", "%3E", "", "\n", "“", "”");
        $content = str_replace($find, $replace, $text);           //微信中替换标签
        $content = strip_tags($content, '<a><img>');
        return str_replace("\r\n", '', rtrim(ltrim($content, ' '), ' '));
    }

    /**
     * @param $materials
     * @param $data
     * 群发消息体
     */
    public function getMassMedia($data)
    {
        list($type, $model) = $data;
        $application = $this->createLoginApplication(getTenantId());
        $material = $application->material;

        if ($type == 'text') {
            return $model;
        }

        $mediaId = $this->getMediaId($material, $model, $type);
        if (!empty($mediaId) && in_array($type, ['voice', 'image', 'news'])) {
            return $mediaId;
        }

        //视频群发消息结构
        if (!empty($mediaId) && $type == 'video') {
            return [$mediaId, $model->title, $model->description];
        }
        //图文生成mediaId
        if (empty($mediaId) && $type == 'news') {
            return $this->createArticle($material, $model);
        }
    }

    /**
     * @param $service 素材业务逻辑（数据库相关）
     * @param $model  素材数据模型
     * @param $material 微信素材接口
     * @return array|Image|Voice
     */
    public function getMediaId($material, $model, $type)
    {
        //判断是否已经存在MediaId
        if (!empty($model->MediaId)) {
            //永久素材
            if (empty($model->media_time)) {
                return $model->MediaId;
            }
            //临时素材
            $timeLimit = strtotime('+3 days', $model->media_time) >= time();
            if (!empty($model->media_time) && $timeLimit) {
                return $model->MediaId;
            }
        }

        //图片素材
        if ($type == 'image') {
            return $this->createImage($material, $model);
        }

        //图文素材
        if ($type == 'news' && config('wechat.create_news_article')) {
            return $this->createArticle($material, $model);
        }

        return '';
    }

    private function createImage($material, $model)
    {
        $path = public_path(ltrim($model->path, '/'));
        $media = $material->uploadImage($path);
        $model->MediaId = $media->media_id;
        $model->save();
        return $media->media_id;
    }

    /**
     * @param $material
     * @param $model
     * @return string
     * 创建微信违章
     */
    private function createArticle($material, $model)
    {
        $sourceUrl = !empty($model->url) ? $model->url : $this->getWapNewsUrl($model->tenant_id, $model->id);
        //不存图文为微信文章
        $path = public_path($model->picurl);

        $media = $material->uploadThumb($path);;
        $mdata = [
            'thumb_media_id' => $media->media_id,
            'title' => $model->title,
            'digest' => $model->description,
            'content_source_url' => $sourceUrl,
            'show_cover' => 1,
        ];
        if (!empty($model->article->content)) {
            $mdata['content'] = strip_tags($model->article->content);
        } else {
            $mdata['content'] = $model->description;
        }

        $article[] = new Article($mdata);
        //多圖文操作
        if (!$model->children->isEmpty()) {
            foreach ($model->children as $mr) {
                $path = public_path($mr->picurl);
                $media = $material->uploadThumb($path);
                $sourceUrl = !empty($mr->url) ? $mr->url : $this->getWapNewsUrl($mr->tenant_id, $mr->id);
                $mdata = [
                    'thumb_media_id' => $media->media_id,
                    'title' => $mr->title,
                    'digest' => $mr->description,
                    'content_source_url' => $sourceUrl,
                ];
                if (!empty($mr->article->content)) {
                    $mdata['content'] = $mr->article->content;
                } else {
                    $mdata['content'] = $mr->title;
                }
                $article[] = new Article($mdata);
            }
        }
        try {
            if (count($article) == 1) {
                $media = $material->uploadArticle($article[0]);
            } else {
                $media = $material->uploadArticle($article);
            }

        } catch (\Exception $e) {
            return $e->getMessage();
        }
        $model->MediaId = $media->media_id;
        $model->save();
        return $media->media_id;
    }

    /**
     * @param $materials
     * @param $data
     * 素材为临时素材
     */
    public function getStaffMedia($data)
    {
        list($type,$model) = $data;
        $application = $this->createLoginApplication(getTenantId());
        if($type == 'news') {
            $material = $application->material;
        } else {
            $material = $application->material_temporary;
        }
        //文本素材
        if($type == 'text') {
            return new Text(['content'=>$model]);
        }

        //图文不上传素材到微信
        if($type == 'news') {
            return $this->createNews($model);
        }

        $mediaId = $this->getMediaId($material, $model, $type);

        if($type == 'image') {
            return new Image(['media_id'=>$mediaId]);
        }


    }

    /**
     * @param $tenantId
     * @param $newsId
     * @return string
     */
    private function getWapNewsUrl($tenantId, $newsId)
    {
        return 'http://' . route_system_domain('wap' . $tenantId) . '/news/' . $newsId;
    }
}
